import Schema from "async-validator"
import {
  orderAddress,
  prePayInfo,
  orderBuy,
  orderInfo,
  submitOrder
} from "@/api/order"
const app = getApp()
Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '选择送达日期', // 期望送达日期
    remarks: '', // 祝福语
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    orderAddress: {}, // 地址信息

  },
  async onLoad(option) {
    // console.log(option);
    if (option.goodsId) {
      const res = await orderBuy(option.goodsId, option.blessing)
      this.setData({
        goodsId:option.goodsId,
        remarks:option.blessing,
        ...res.data
      })
    } else {
      this.getOrdarInfo()
    }
    this.getAddress()
  },

  onShow() {
    // 如果app有值则使用app的地址
    const res = app.globalData.address
    if (!res) this.getAddress()
    this.setData({
      orderAddress: res
    })
  },
  // 获取收获地址
  async getAddress() {
    const res = await orderAddress()
    this.setData({
      orderAddress: res.data
    })
  },
  // 获取订单详情的数据
  async getOrdarInfo() {
    const {
      code,
      data
    } = await orderInfo()
    console.log(code);
    console.log(data);

    if (code === 200) {
      const orderGoods = data.cartVoList.find(item => {
        return item.blessing !== ''
      })
      this.setData({
        ...data,
        remarks: orderGoods && orderGoods.blessing
      })
    }
  },
  // 期望送达日期
  onShowDateTimerPopUp(e) {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    this.setData({
      show: false,
      deliveryDate: new Date(parseInt(event.detail)).toLocaleString().substr(0, 10)
    })
    console.log(new Date(parseInt(event.detail)).toLocaleString());
    console.log(new Date(parseInt(event.detail)));
  },

  // 期望送达日期取消按钮
  onCancelTimePicker() {
    this.setData({
      show: false
    })
  },

  // 添加收获地址  跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/settingModule/pages/address/list/index'
    })
  },
  // 提交订单
  async submitOrder() {
    const {valid} = await this.orderInfoValidator()
    if (!valid) return
    const {
      buyName,
      buyPhone,
      cartList=this.data.cartVoList,
      deliveryDate,
      remarks,
      userAddressId=this.data.orderAddress.id
    } =this.data
    const params={
      buyName,
      buyPhone,
      cartList,
      deliveryDate,
      remarks,
      userAddressId
    }
    const {code,data,message} = await submitOrder(params)
    if(code===200){
      wx.showToast({
        title: '提交订单'+message,
        icon:"success"
      })
      // 在平台订单创建以后,需要将后端请求微信api的数据返回 订单编号
      this.orderNo=data
    }
    this.advancePay()
  },
  // 获取微信预支付信息
  async advancePay(){
  try {
    const res =await prePayInfo(this.orderNo)
    console.log(res.data);
    if(res.code==200){
      const payInfo =await wx.requestVirtualPayment(res.data)
      // const payInfo = await wx.requestPayment(res.data)
      console.log(payInfo)
    }
  } catch (error) {
    wx.showToast({
    title: '支付失败,联系客服',
    icon:"none"
    })
  }
  },
  // 弹框关闭
  onClose() {},
  onUnload() {
    app.globalData.address = {}
  },

  // 校验输入信息
  orderInfoValidator() {
    const phoneRegExp = `^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$`
    const dataRegExp = /^\d{4}\/\d{1,2}\/\d{1,2}$/;
    const rules = {
      "buyName": [{
          required: true,
          message: "订购人姓名不为空"
        },
        {
          min: 2,
          max: 5,
          message: "输入长度不合法"
        },
      ],
      "buyPhone": [{
          required: true,
          message: "手机号不为空"
        },
        {
          pattern: phoneRegExp,
          message: "手机号输入不正确"
        }
      ],
      "deliveryDate": [{
          required: true,
          message: "期望送达时间不为空"
        },
        {
          pattern: dataRegExp,
          message: "期望送达时间不正确"
        }
      ]
    }
    const validator = new Schema(rules)
    const params = this.data
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          wx.showToast({
            title: errors[0].message,
            icon: "none"
          })
          resolve({
            valid: false
          })
        } else {
          resolve({
            valid: true
          })
        }
      })
    })
  },

})